import { useRef, useState, useEffect } from 'react'
/* -------------------------------------------------------- Declare -- */
const { $lazy, $, $http, $config } = window
/* -------------------------------------------------------- Async Component -- */
import Backup from './_config/backup'
import BackupAll from './_config/backup-all'
const ListComponent = $lazy.hook(()=>import('./opt/list'))
const TableComponent = $lazy.hook(()=>import('./opt/table'))
const Page = $lazy.load(()=>import('#tp/content/page-content'))
/* -------------------------------------------------------- Page Component -- */
const Index = () => {
	const tableRef = useRef()
	const recordRef = useRef()
	const [ name, setName ] = useState()
	const [info, setInfo] = useState({ title:'', db:'' })
	useEffect(()=>{
		$http.pull(null, 'project/info', { loading:true }).then( d => {
			if(d) setInfo({ ...d, db:d.database, url: encodeURIComponent(d.mongodb)})
		})
	},[])
	const controls = [
		!$config.isNative ? null : { label:'备份全部', mode:'formModal', ghost:1, isKeys:1, config:() => BackupAll({ backup:info.backup } )},
		!$config.isNative ? null : { label:'备份单个数据库', mode:'formModal', ghost:1, isKeys:1, config:() => Backup({ backup:info.backup, database:info.db } )},
		{ mode:'refresh' }
	]
	return (
		info.db && (
			<Page title={`gridfs 管理 - ${ info.db }`} controls={controls}>
				<div className='fx ex' style={{gap:0}}>
					<div className='fv rel' style={{width:380}}>
						{
							info?.db && (
								<TableComponent ref={tableRef} listRef={recordRef} url={info.url} db={info.db} onChange={ ({ name, is_gridfs }) => {
									setName(name)
									if(is_gridfs){
										$.ref(recordRef).search({ api: 'mongodb/gridfs_bucket_list/' + name, param: { url:info.url, db:info.db }})
									}
								}}/>
							)
						}
					</div>
					<div className='fv rel ex'>
						<ListComponent dbRef={tableRef} ref={recordRef} url={info.url} db={info.db} name={name}/>
					</div>
				</div>
			</Page>
		)
	)
}
export default Index